<template>
  <view class="container">
    <view>
      <block v-for="(item, index) in prodList" :key="index">
        <production :item="item" />
      </block>

      <view>
        <view>
          <form @submit="formSubmit" @reset="formReset">
            <view class="uni-form-item uni-column" style="display: flex;align-self: center;margin-top: 60rpx;">
              <view class="uni-input-label">客户姓名：</view>
              <input class="uni-input-custom" name="input" placeholder="请输入客户姓名" />
            </view>
            <view class="uni-form-item uni-column" style="display: flex;align-self: center;margin: 15px 0;">
              <view class="uni-input-label">电话：</view>
              <input class="uni-input-custom" name="input" placeholder="请输入客户电话" />
            </view>
            <view class="uni-form-item uni-column" style="display: flex;align-self: center;margin: 15px 0;">
              <view class="uni-input-label">地址：</view>
              <input class="uni-input-custom" name="input" placeholder="请输入地址" />
            </view>
            <view class="uni-form-item uni-column" style="display: flex;align-self: center;margin: 15px 0;">
              <view class="uni-input-label">维修项：</view>
              <input class="uni-input-custom" name="input" placeholder="请输入维修项" />
            </view>
            <view class="uni-form-item uni-column" style="display: flex;align-self: center;margin: 15px 0;">
              <view class="uni-input-label">完成情况：</view>
              <input class="uni-input-custom" name="input" placeholder="请输入完成情况" />
            </view>
            <view class="uni-form-item uni-column" style="display: flex;align-self: center;margin: 15px 0;">
              <view class="uni-input-label">客户签字：</view>
              <view v-if="isSign">
                <image :src="signatureImage" class="signature-preview" />
                <span @click="togglePopup" style="margin-bottom: 4rpx;">修改</span>
                <span @click="clearSign" style="margin-bottom: 10px;margin-left: 10rpx;">清除</span>
              </view>
              <view v-if="!isSign">
                <button @click="togglePopup" type="default">点击签字</button>
              </view>

            </view>
            <view class="uni-form-item uni-column" style="display: flex;align-self: center;margin: 15px 0;">
              <view class="uni-input-label">地址：</view>
              <input class="uni-input-custom" name="input" placeholder="请输入地址" />
            </view>


            <!--       <view class="uni-form-item uni-column" style="display: flex; align-self: center; margin: 15px 0;">
              <view class="uni-input" style="margin: 0 20rpx; width: 25%;">选择日期：</view>
              <picker style="width: 50%;" mode="date" start="2024-01-01" end="2025-12-31" @change="handleDateChange">
                <view class="uni-input-custom">
                  {{ selectedDate || '选择时间' }}
                </view>
              </picker>
            </view> -->



            <view class="uni-form-item uni-column" style="display: flex;align-self: center;margin: 15px 0;">
              <view class="uni-input" style="margin:0 20rpx;width: 25%;">选择日期：</view>
              <!-- 包裹 picker 的外层 view -->
              <view style="width: 50%; height: 40rpx;">
                <picker style="width: 100%; height:40rpx;" mode="date" start="2024-01-01" end="2025-12-31"
                  @change="handleDateChange">
                  <view class="uni-input-custom"
                    style="background-color: gainsboro; border: 1rpx solid grey; border-radius: 4px; padding: 8rpx;">
                    {{ selectedDate || '选择时间' }}
                  </view>
                </picker>
              </view>
            </view>


            <view style="margin-top: 80rpx;" class="uni-btn-v">
              <button class="uni-btn" @click="getqingqiu">get请求</button>
              <button class="uni-btn" @click="postqingqiu">post请求</button>
              <button class="uni-btn" @click="submitForm">提交</button>
              <button style="margin-top: 20rpx;" class="uni-btn uni-btn-default" @click="clearData" type="default"
                form-type="reset">重填</button>
            </view>
            <!--    <view class="signature-container" v-if="true">
              <image :src="signatureImage.value" class="signature-preview" />
              <span>签名预览</span>

              <view>{{signatureImage}}</view>
            </view> -->


          </form>
        </view>
      </view>



      <!-- 控制开关 -->
      <!-- <button @click="togglePopup">显示/隐藏弹窗</button> -->

      <!-- 弹窗组件 -->
      <view class="popup" v-if="open">
        <view class="popup-content">
          <view class="box" v-show="modelValue" :style="{ height: '100%' }">
            <view class="whole canvas-autograph flexc">
              <canvas class="scroll-view" canvas-id="mycanvas" @touchstart="touchstart" @touchmove="touchmove"
                disable-scroll="true" @touchend="touchend" />
              <view class="fun-box ">
                <van-button round block type="warning" size="small" @click="clear">
                  清空
                </van-button>
                <van-button round block type="primary" size="small" @click="confirm">
                  确认
                </van-button>
                <van-button round block type="danger" size="small" @click="cancel">
                  取消
                </van-button>
                <van-button round block type="danger" size="small" @click="closePopup">
                  关闭
                </van-button>
                <!-- <button @click="closePopup">关闭</button> -->
              </view>
            </view>
            <image v-if="showSignature1" :src="signatureImage" class="signature-image" />

          </view>






        </view>
      </view>

      <!--  <view>
        <image :src="imageData" class="image" />
      </view> -->

      <!--
      传入图片
      <view>
        <image :src="signatureImage" class="signature-preview" />
      </view> -->



      <view v-if="!prodList.length" class="empty">
        暂无数据
      </view>
    </view>
  </view>
</template>

<script setup>
  // import uni from 'uni-request';






  import {
    onMounted
  } from 'vue'

  let isSign = ref(true)
  let imageData = ref(
    ""
  )



  let signatureImage = ref('')


  //get请求
  function getqingqiu() {

    // 假设你的 token 是固定的，你可以将其定义为常量
    const token =
      'eyJhbGciOiJIUzI1NiJ9.eyJlbXBJZCI6MSwiZXhwIjoxNzExNzEwNTM5fQ.vTiky2Tl2aNv8mVGI-irgDba0AWkg5CeIyTs1v0hiHs';

    uni.request({
      url: 'http://localhost:8080/admin/employee/2', // 请求的 URL
      method: 'GET', // 请求方法，此处为 GET
      data: {
        // 如果有需要，可以在这里添加 GET 请求的参数
        // 例如：name: 'value'
      },
      header: {
        'token': "eyJhbGciOiJIUzI1NiJ9.eyJlbXBJZCI6MSwiZXhwIjoxNzExNzEwNTM5fQ.vTiky2Tl2aNv8mVGI-irgDba0AWkg5CeIyTs1v0hiHs", // 将 token 添加到 Authorization 头中
      },
      success: (res) => {
        // 请求成功的回调函数
        console.log('请求成功', res);
        // 可以在这里处理返回的数据
      },
      fail: (err) => {
        // 请求失败的回调函数
        console.error('请求失败', err);
      }
    });


  }

  //post请求
  function postqingqiu() {

    // 假设你的 token 是固定的，你可以将其定义为常量
    const token =
      'eyJhbGciOiJIUzI1NiJ9.eyJlbXBJZCI6MSwiZXhwIjoxNzExNzEwNTM5fQ.vTiky2Tl2aNv8mVGI-irgDba0AWkg5CeIyTs1v0hiHs';

    // 定义要发送的数据
    const postData = {
      // 根据需要添加POST请求的参数
      // 例如：name: 'value'
      idNumber: "12399",
      name: "嘻嘻嘻",
      phone: "16692167099",
      sex: "1",
      username: "000"
    };

    uni.request({
      url: 'http://localhost:8080/admin/employee', // 请求的 URL
      method: 'POST', // 请求方法，此处为 POST
      data: postData, // 发送的数据
      header: {
        'content-type': 'application/json', // 设置请求头为JSON格式
        'token': token // 将 token 添加到 Authorization 头中
      },
      success: (res) => {
        // 请求成功的回调函数
        console.log('请求成功', res);
        // 可以在这里处理返回的数据
      },
      fail: (err) => {
        // 请求失败的回调函数
        console.error('请求失败', err);
      }
    });
  }





  // 在页面加载时获取签字图片路径
  onMounted(() => {



    uni.getStorage({
      key: 'signatureImage',
      success: function(res) {
        // 获取成功，将签字图片路径赋值给 signatureImage
        signatureImage.value = res.data;
        console.log(signatureImage.value)
      },
      fail: function() {
        // 获取失败，处理失败情况
        console.log('获取签名图片信息失败');
      }
    });
  })



  // 控制弹窗显示与隐藏的变量
  const open = ref(false);

  // 打开弹窗
  const togglePopup = () => {
    open.value = !open.value;
  };

  // 关闭弹窗
  const closePopup = () => {
    open.value = false;
  };
  const clearSign = () => {
    isSign.value = false;
  };
  // uni.getStorage({
  //   key: 'signatureImage',
  //   success: function(res) {
  //     // 获取成功，res.data 中存储了签名图片的临时文件路径
  //     signatureImage.value = res.data;
  //     // 在页面中展示签名图片
  //     console.log("数据" + signatureImage.value)
  //     // signatureImage.value = signatureImage; // 这里的 this 指向页面的实例，根据实际情况使用
  //     // console.log("1111" + signatureImage.value)
  //   },
  //   fail: function() {
  //     // 获取失败，可能是签名图片信息不存在
  //     console.log('获取签名图片信息失败');
  //   }
  // });
  let show = ref(false)

  function startSign() {
    console.log(111)
    show.value = true
  }




  function clearData() {

    selectedDate.value = ""


  }

  // 导入 ref
  import {
    ref
  } from 'vue';

  // 定义响应式变量 selectedDate
  const selectedDate = ref('');

  // 处理日期变更事件
  const handleDateChange = (event) => {
    selectedDate.value = event.detail.value;
  };
  const sts = ref(0)
  const title = ref('')
  const current = ref(1)
  const size = ref(10)
  const pages = ref(0)
  const tagid = ref(0)
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad((options) => {
    current.value = 1
    pages.value = 0
    sts.value = options.sts
    title.value = options.title ? options.title : ''

    if (options.tagid) {
      tagid.value = options.tagid
    }

    if (sts.value == 0) {
      if (options.tagid == 1) {
        uni.setNavigationBarTitle({
          title: '每日上新'
        })
      } else if (options.tagid == 2) {
        uni.setNavigationBarTitle({
          title: '商城热卖'
        })
      } else if (options.tagid == 3) {
        uni.setNavigationBarTitle({
          title: '更多宝贝'
        })
      }
    } else if (sts.value == 1) {
      uni.setNavigationBarTitle({
        title: '新品推荐'
      })
    } else if (sts.value == 2) {
      uni.setNavigationBarTitle({
        title: '限时特惠'
      })
    } else if (sts.value == 3) {
      uni.setNavigationBarTitle({
        title: '每日疯抢'
      })
    } else if (sts.value == 4) {
      uni.setNavigationBarTitle({
        title: '优惠券活动产品'
      })
    } else if (sts.value == 5) {
      uni.setNavigationBarTitle({
        title: '我的收藏产品'
      })
    } else {
      uni.setNavigationBarTitle({
        title: title.value
      })
    }

    // loadProdData(options)
  })

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom(() => {
    if (current.value < pages.value) {
      current.value = current.value + 1
      loadProdData()
    }
  })

  /**
   * 加载产品数据
   */
  const loadProdData = (options) => {
    const stsParam = sts.value

    if (stsParam == 0) {
      // 分组标签产品列表
      getTagProd()
    } else if (stsParam == 1) {
      // 新品推荐
      const url = '/prod/lastedProdPage'
      getActProd(url)
    } else if (stsParam == 2) {
      // 限时特惠
      const url = '/prod/discountProdList'
      getActProd(url)
    } else if (stsParam == 3) {
      // 每日疯抢
      const url = '/prod/moreBuyProdList'
      getActProd(url)
    } else if (stsParam == 4) {
      // 优惠券产品列表
      getProdByCouponId(options.tagid)
    } else if (stsParam == 5) {
      // 收藏产品列表
      getCollectionProd()
    }
  }

  const prodList = ref([])
  const getActProd = (url) => {
    uni.showLoading()
    http.request({
        url,
        method: 'GET',
        data: {
          current: current.value,
          size: size.value
        }
      })
      .then(({
        data
      }) => {
        let list
        if (data.current === 1) {
          list = data.records
        } else {
          list = prodList.value
          list = list.concat(data.records)
        }
        prodList.value = list
        pages.value = data.pages
        uni.hideLoading()
      })
  }

  /**
   * 获取我的收藏产品
   */
  // const getCollectionProd = () => {
  //   uni.showLoading()
  //   http.request({
  //       url: '/p/user/collection/prods',
  //       method: 'GET',
  //       data: {
  //         current: current.value,
  //         size: size.value
  //       }
  //     })
  //     .then(({
  //       data
  //     }) => {
  //       let list
  //       if (data.current == 1) {
  //         list = data.records
  //       } else {
  //         list = prodList.value
  //         list = list.concat(data.records)
  //       }
  //       prodList.value = list
  //       pages.value = data.pages
  //       uni.hideLoading()
  //     })
  // }



  import {
    reactive
  } from 'vue'

  let points = reactive([])
  let canvaCtx = reactive(uni.createCanvasContext('mycanvas'))
  let modelValue = ref(true)
  let showSignature1 = ref(false) // 控制签名图片的显示状态
  let showSignature2 = ref(false) // 控制签名图片的显示状态
  // let signatureImage = ref('') // 保存签名图片的临时文件路径

  canvaCtx.lineWidth = 4;
  canvaCtx.lineCap = 'round'
  canvaCtx.lineJoin = 'round'

  const touchstart = e => {
    let startX = e.changedTouches[0].x
    let startY = e.changedTouches[0].y
    let startPoint = {
      X: startX,
      Y: startY
    }
    points.push(startPoint);
    canvaCtx.beginPath();
  }

  const touchmove = e => {
    let moveX = e.changedTouches[0].x
    let moveY = e.changedTouches[0].y
    let movePoint = {
      X: moveX,
      Y: moveY
    }
    points.push(movePoint)
    draw()
  }

  const draw = () => {
    let len = points.length
    if (len >= 2) {
      let point1 = points[len - 2]
      let point2 = points[len - 1]
      canvaCtx.moveTo(point1.X, point1.Y)
      canvaCtx.lineTo(point2.X, point2.Y)
      canvaCtx.stroke()
      canvaCtx.draw(true)
    }
  }

  const touchend = e => {
    // points = [];
  }

  const clear = () => {
    points = []
    return uni.getSystemInfo()
      .then(res => {
        canvaCtx.clearRect(0, 0, res.windowWidth, res.windowHeight);
        canvaCtx.draw(true);
        return res
      })
      .catch(err => {
        console.log(err);
      })
  }

  const confirm = () => {
    if (points.length < 1) {
      uni.showToast({
        icon: 'none',
        title: '请签字'
      })
    } else {
      uni.canvasToTempFilePath({
        canvasId: 'mycanvas',
      }).then(res => {
        const {
          tempFilePath
        } = res
        signatureImage.value = tempFilePath // 将临时文件路径保存到数据属性中
        showSignature2.value = true // 显示签名图片
        console.log('签字图片信息:', tempFilePath) // 打印签字图片信息
        // 将签字图片信息存储到本地缓存
        uni.setStorage({
          key: 'signatureImage',
          data: tempFilePath,
          success: function() {
            console.log('签字图片已存储到本地')
            open.value = false;
            isSign.value = true


          }
        })
      })

    }
  }

  const cancel = () => {
    clear().then((res) => {
      console.log('取消签名')
    })
  }


  /**
   * 获取标签列表
   */
  // const getTagProd = () => {
  //   uni.showLoading()
  //   http.request({
  //       url: '/prod/prodListByTagId',
  //       method: 'GET',
  //       data: {
  //         tagId: tagid.value,
  //         current: current.value,
  //         size: size.value
  //       }
  //     })
  //     .then(({
  //       data
  //     }) => {
  //       let list
  //       if (data.current === 1) {
  //         list = data.records
  //       } else {
  //         list = prodList.value.concat(data.records)
  //       }
  //       prodList.value = list
  //       pages.value = data.pages
  //       uni.hideLoading()
  //     })
  // }

  /**
   * 获取优惠券产品列表
   */
  // const getProdByCouponId = (id) => {
  //   uni.showLoading()
  //   http.request({
  //       url: '/coupon/prodListByCouponId',
  //       method: 'GET',
  //       data: {
  //         couponId: id,
  //         current: current.value,
  //         size: size.value
  //       }
  //     })
  //     .then(({
  //       data
  //     }) => {
  //       let list
  //       if (data.current === 1) {
  //         list = data.records
  //       } else {
  //         list = prodList.value.concat(data.records)
  //       }
  //       prodList.value = list
  //       pages.value = data.pages
  //       uni.hideLoading()
  //     })
  // }
</script>

<style scoped lang="scss">
  @use './prod-classify.scss';

  .box {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    background-color: #ffffff;
  }

  .whole {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }

  .scroll-view {
    width: 100%;
    height: 400px;
    background-color: #ffffff;
    border: 1px solid #000000;
  }

  .fun-box {
    width: 100%;
    display: flex;
    justify-content: space-around;
    margin-top: 20px;
  }

  /* 添加用于展示签名的区域样式 */
  .signature-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-top: 20px;
  }

  .signature-preview {
    width: 200px;
    height: auto;
  }

  .signature-container span {
    margin-top: 10px;
    font-size: 14px;
  }

  /* 弹窗样式，根据需要自行修改 */
  .popup {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .popup-content {
    background-color: white;
    padding: 20px;
    border-radius: 10px;
  }

  /* 添加用于展示签名的区域样式 */
  .signature-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-top: 20px;
  }

  .signature-preview {
    background-color: white;
    border: 1px solid #808080;
    width: 200rpx;
    height: 80rpx;
  }

  .signature-container span {
    margin-top: 10px;
    font-size: 14px;
  }

  .uni-form-item .title {
    padding: 20rpx 0;
  }

  /* 自定义输入框标签样式 */
  .uni-input-label {
    margin: 0 20rpx;
    width: 25%;
  }

  /* 自定义输入框样式 */
  .uni-input-custom {
    border: 1rpx solid grey;
    border-radius: 4px;
    /* 设置边框圆角 */
    padding: 8rpx;
    /* 设置内边距 */
    flex: 1;
    /* 占据剩余空间 */
  }

  .uni-btn {
    background-color: #007bff;
    color: #fff;
    border: 1px solid #007bff;
    margin-left: 20rpx;
    /* 调整按钮之间的间距 */
  }

  .uni-btn-default {
    background-color: #fff;
    color: #007bff;
    border: 1px solid #007bff;
    margin-left: 20rpx;
    /* 调整按钮之间的间距 */
  }
</style>